const path = require('path');

//导入连接数据库模块
const connectSql = require(path.join(__dirname,"../tool/connect.js"))

//获取学生列表页面
const getStudentListPage = (req, res) => {
    const keywords = req.query.keywords || '';
     //1连接数据库

     connectSql.findList('studentInfo',{name:{$regex:keywords}},(err, docs)=>{
        //  console.log(docs);
        res.render(path.join(__dirname,"../static/view/list.html"), { students:docs,keywords,loginName:req.session.loginName});
     });
}

//获取新增学生页面
const getAddStudentPage = (req,res) => {
    res.render(path.join(__dirname,"../static/view/add.html"), { });
}

//新增学生逻辑处理
const addStudent = (req,res)=>{
 
    connectSql.insert('studentInfo',req.body, (err, resu)=> {
            if (resu == null) {
                res.send('<script>alert("插入失败");</script>');
            }else{
                res.send("<script>window.location.href='/studentManager/list'</script>")
            }
    })

    // console.log(req.body);   
    // MongoClient.connect(url, function (err, client) {
    //     const db = client.db(dbName);
    //     const collection = db.collection('studentInfo');
    //     collection.insertOne(req.body,  (err, resu)=> {
    //         client.close();
    //         if (resu == null) {
    //             res.send('<script>alert("插入失败");</script>');
    //         }else{
    //             res.send("<script>window.location.href='/studentManager/list'</script>")
    //         }
    //     });
    // });
}

//获取修改学生页面
const getEditStudentPage = (req,res)=>{
    const studentId = req.params.studentId;

    connectSql.findOne('studentInfo',{_id:connectSql.ObjectId(studentId)},(err, docs)=>{
        res.render(path.join(__dirname,"../static/view/edit.html"), {studentInfo:docs});
    });
}

//修改学生信息逻辑处理
const getUpdateStudentInfo = (req,res) =>{
    const studentId = req.params.studentId;
    connectSql.update('studentInfo',{_id:connectSql.ObjectId(studentId)},req.body,(err,resu)=>{
        if (resu == null) { 
            res.send('<script>alert("修改失败")</script>')
        }else{
            res.send("<script>location.href = '/studentManager/list'</script>");
        }
    })
}


//删除学生
const DelteStudent = (req,res) =>{
    const studentId = req.params.studentId;
    console.log(studentId);
    connectSql.deleteStudent('studentInfo',{_id:connectSql.ObjectId(studentId)},(err,resu)=>{
        if (resu == null) { 
            res.send('<script>alert("删除失败")</script>')
        }else{
            res.send("<script>location.href = '/studentManager/list'</script>");
        }
    })
}


module.exports = {
    getStudentListPage,
    getAddStudentPage,
    addStudent,
    getEditStudentPage,
    getUpdateStudentInfo,
    DelteStudent
}